import { PageContext } from "./page-context";
import { createLifeProgressChart } from "./part-life-chart";
import type { DevicePartResponse } from "../../tyeps/device-part-response";

type PartLifeInfo = {
  name: string;
  id: string;
  deviceId: string;
  life: number;
  currentLife: number;
};

PageContext.onLoaded((viewModel) => {
  const partLifeInfos: PartLifeInfo[] = [];

  viewModel.deviceMaintenanceList.map((deviceItem) => {
    if (deviceItem.parts.length > 0) {
      let currentPart: DevicePartResponse = deviceItem.parts[0];

      for (let index = 1; index < deviceItem.parts.length; index++) {
        const indexItem = deviceItem.parts[index];
        // 筛选出寿命比例最高的部件
        if (
          (indexItem.currentLifetime - indexItem.accumulatedDowntime) * 100 >
          (currentPart.currentLifetime - currentPart.accumulatedDowntime) * 100
        ) {
          currentPart = indexItem;
        }
      }

      partLifeInfos.push({
        name: deviceItem.device.deviceName + "-" + currentPart.devicePartName,
        id: currentPart.id,
        deviceId: deviceItem.device.id,
        life: currentPart.accumulatedDowntime,
        currentLife: currentPart.currentLifetime,
      });
    }
  });

  partLifeInfos.sort(
    (a, b) =>
      Math.floor((b.currentLife / b.life) * 100) -
      Math.floor((a.currentLife / a.life) * 100)
  );

  createLifeProgressChart(partLifeInfos, viewModel.processName === "pulping");
});
